﻿using PersonnelStatistics.DAL;
using PersonnelStatistics.Entities;

namespace PersonnelStatistics.BLL
{
    public class PersonalService
    {
        private readonly MyDbContext _dbContext;
        public PersonalService()
        {
            _dbContext = new MyDbContext();
        }

        public Personal GetSingle(int id)
            => _dbContext.Table.Find(id);

        public List<Personal> GetList(string search = null)
        {
            var query = _dbContext.Table;
            if (string.IsNullOrWhiteSpace(search))
            {
                return query.ToList();
            }
            else
            {
                return query.Where(w =>
                    w.姓名.Contains(search) ||
                    w.住址.Contains(search) ||
                    w.电话.Contains(search))
                 .ToList();
            }
        }

        public void AddOrUpdate(Personal personal)
        {
            if (personal.Id == default)
            {
                _dbContext.Add(personal);
            }
            else //更新
            {
                var entity = _dbContext.Table.Find(personal.Id);
                entity.姓名 = personal.姓名;
                entity.住址 = personal.住址;
                //省，时间问题

                if (string.IsNullOrWhiteSpace(entity.姓名))
                {
                    throw new Exception("姓名不能为空");
                }
            }
            _dbContext.SaveChanges();
        }

        public void Delete(int id)
        {
            var personal = _dbContext.Table.Find(id);
            _dbContext.Remove(personal);

            _dbContext.SaveChanges();
        }

    }
}
